package com.zp.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.base.api.entity.ClinicItemDict;
import com.zp.base.entity.bo.ClinicItemDictBo;
import com.zp.base.entity.bo.PriceListBo;
import com.zp.base.entity.vo.ClinicItemDictVo;
import com.zp.base.entity.vo.PriceListVo;
import com.zp.base.mapper.ClinicItemDictMapper;
import com.zp.base.mapper.PriceListMapper;
import com.zp.base.service.IClinicItemDictService;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 诊疗项目Service业务层处理
 *
 * @author zhang peng
 * @date 2023-01-08
 */
@RequiredArgsConstructor
@Service
public class ClinicItemDictServiceImpl implements IClinicItemDictService {

    private final ClinicItemDictMapper baseMapper;

    private final PriceListMapper priceListMapper;

    /**
     * 查询诊疗项目
     */
    @Override
    public ClinicItemDictVo queryById (String clinicItemId) {
        return baseMapper.selectVoById(clinicItemId);
    }

    /**
     * 查询诊疗项目列表(分页)
     */
    @Override
    public TableDataInfo<ClinicItemDictVo> queryPageList (ClinicItemDictBo bo, PageQuery pageQuery) {
        Map<String, Double> stringListMap = tissueControl();
        LambdaQueryWrapper<ClinicItemDict> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(ClinicItemDict::getItemClass);
        Page<ClinicItemDictVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(item -> {
            item.setSubTotal(stringListMap.get(item.getClinicItemId()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * list分组后求和
     *
     * @return
     */
    public Map<String, Double> tissueControl () {
        Map<String, Double> map = new HashMap<>();
        List<PriceListVo> priceListVoList = priceListMapper.selectContrastExist(new PriceListBo());
        priceListVoList.forEach(item -> {
            item.setSubTotal(item.getPrice().doubleValue() * item.getClinicVsPriceVo().getAmount());
        });
        Map<String, List<PriceListVo>> collect = priceListVoList.stream().collect(Collectors.groupingBy(PriceListVo::getClinicItemId, Collectors.toList()));
        collect.forEach((key, list) ->
                map.put(key, list.stream().mapToDouble(PriceListVo::getSubTotal).sum())
        );
        return map;

    }

    /**
     * 查询诊疗项目列表(不分页)
     */
    @Override
    public List<ClinicItemDictVo> queryList (ClinicItemDictBo bo) {
        Map<String, Double> stringListMap = tissueControl();
        LambdaQueryWrapper<ClinicItemDict> lqw = autoBuildQueryWrapper(bo);
        List<ClinicItemDictVo> list = baseMapper.selectVoList(lqw);
        list.forEach(item -> {
            item.setSubTotal(stringListMap.get(item.getClinicItemId()));
        });
        return list;
    }

    private LambdaQueryWrapper<ClinicItemDict> autoBuildQueryWrapper (ClinicItemDictBo bo) {
        LambdaQueryWrapper<ClinicItemDict> lqw = Wrappers.lambdaQuery();
        lqw.eq(ClinicItemDict::getOrgId, bo.getOrgId());
        lqw.notIn(CollectionUtil.isNotEmpty(bo.getNotInSelect()), ClinicItemDict::getItemClass, bo.getNotInSelect());
        if (bo.getIsFiltrationContrastExist()) {
            lqw.last("order by length(item_name) asc limit 20");
        }
        lqw.and(StringUtils.isNotEmpty(bo.getItemInfo()), wrapper -> wrapper
                .like(ClinicItemDict::getItemName, bo.getItemInfo())
                .or().like(ClinicItemDict::getItemCode, bo.getItemInfo())
                .or().like(ClinicItemDict::getInputCode, bo.getItemInfo())
        );
        return lqw;
    }

    private LambdaQueryWrapper<ClinicItemDict> buildQueryWrapper (ClinicItemDictBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ClinicItemDict> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getItemClass()), ClinicItemDict::getItemClass, bo.getItemClass());
        lqw.eq(StringUtils.isNotBlank(bo.getItemCode()), ClinicItemDict::getItemCode, bo.getItemCode());
        lqw.like(StringUtils.isNotBlank(bo.getItemName()), ClinicItemDict::getItemName, bo.getItemName());
        lqw.eq(StringUtils.isNotBlank(bo.getPerformedBy()), ClinicItemDict::getPerformedBy, bo.getPerformedBy());
        lqw.eq(StringUtils.isNotBlank(bo.getInputCode()), ClinicItemDict::getInputCode, bo.getInputCode());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), ClinicItemDict::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getExpand1()), ClinicItemDict::getExpand1, bo.getExpand1());
        lqw.eq(StringUtils.isNotBlank(bo.getExpand2()), ClinicItemDict::getExpand2, bo.getExpand2());
        lqw.eq(StringUtils.isNotBlank(bo.getExpand3()), ClinicItemDict::getExpand3, bo.getExpand3());
        lqw.eq(StringUtils.isNotBlank(bo.getExpand4()), ClinicItemDict::getExpand4, bo.getExpand4());
        lqw.eq(StringUtils.isNotBlank(bo.getExpand5()), ClinicItemDict::getExpand5, bo.getExpand5());
        lqw.eq(StringUtils.isNotBlank(bo.getIsMeal()), ClinicItemDict::getIsMeal, bo.getIsMeal());
        lqw.like(StringUtils.isNotBlank(bo.getIcd9Name()), ClinicItemDict::getIcd9Name, bo.getIcd9Name());
        lqw.eq(StringUtils.isNotBlank(bo.getIcd9Code()), ClinicItemDict::getIcd9Code, bo.getIcd9Code());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationId()), ClinicItemDict::getOperationId, bo.getOperationId());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationRegiste()), ClinicItemDict::getOperationRegiste, bo.getOperationRegiste());
        return lqw;
    }

    /**
     * 新增诊疗项目
     */
    @Override
    public Boolean insertByBo (ClinicItemDictBo bo) {
        ClinicItemDict add = BeanUtil.toBean(bo, ClinicItemDict.class);
        validEntityBeforeSave(add);
        add.setDelFlag("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setClinicItemId(add.getClinicItemId());
        }
        return flag;
    }

    /**
     * 修改诊疗项目
     */
    @Override
    public Boolean updateByBo (ClinicItemDictBo bo) {
        ClinicItemDict update = BeanUtil.toBean(bo, ClinicItemDict.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (ClinicItemDict entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除诊疗项目
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
